//
//  BirthdayAppendViewController.swift
//  FearfulNotification
//
//  Created by 筱鹏 on 2018/1/16.
//  Copyright © 2018年 筱鹏. All rights reserved.
//

import UIKit

extension Notification.Name {
    static let AddNewBirthday: Notification.Name = Notification.Name(rawValue: "AddNewBirthday")
}

class BirthdayAppendViewController: BaseViewController {
    
    let cellID = "BirthdayAppendCellID"
    let pickerCellID = "BirthdayDatePickerCellID"
    var birthdayId: Int64?
    
    var tableView: UITableView!
    var tableViewImplement: BirthdayAppendTableViewImplement!
    
    convenience init(birthdayId: Int64?) {
        self.init()
        self.birthdayId = birthdayId
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.title = "添加农历生日"
        self.view.backgroundColor = Theme.color.background
        self.configSubview()
        self.registerNotification()
        // Do any additional setup after loading the view.
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.dismiss(animated: true, completion: nil)
    }
    
    func configSubview() {
        self.navigationItem.hidesBackButton = true
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .plain, target: self, action: .leftItemSel)
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "保存", style: .plain, target: self, action: .rightItemSel)
        
        tableView = UITableView(frame: self.view.bounds, style: .grouped)
        tableView.register(BirthdayAppendCell.self, forCellReuseIdentifier: cellID)
        tableView.register(BirthdayDatePicker.self, forCellReuseIdentifier: pickerCellID)
        tableView.backgroundColor = Theme.color.background
        tableView.isScrollEnabled = false
        self.view.addSubview(tableView)
        
        tableViewImplement = BirthdayAppendTableViewImplement(tableView: tableView, birthdayId: birthdayId)
    }
    
    func registerNotification() {
        NotificationCenter.default.addObserver(self, selector: .keyboardChangeSel, name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
    }
}

private extension Selector {
    static let leftItemSel = #selector(BirthdayAppendViewController.dismissViewConroller)
    static let rightItemSel = #selector(BirthdayAppendViewController.saveBirthday)
    static let keyboardChangeSel = #selector(BirthdayAppendViewController.keyboardChangeAction(sender:))
}

extension BirthdayAppendViewController {
    class func show(fromVC: BaseViewController, birthdayId: Int64?) {
        let vc = BirthdayAppendViewController(birthdayId: birthdayId)
        fromVC.show(vc, sender: fromVC)
    }
    
    class func present(fromVC: BaseViewController, birthdayId: Int64?) {
        let vc = BirthdayAppendViewController(birthdayId: birthdayId)
        let navigationVC = BaseNavigationController(rootViewController: vc)
        fromVC.present(navigationVC, animated: true, completion: nil)
    }
}

extension BirthdayAppendViewController {
    @objc func dismissViewConroller() {
        view.endEditing(true)
        self.navigationController?.dismiss(animated: true, completion: nil)
    }
    
    @objc func saveBirthday() {
        ProcessHUD.showLoading()
        view.endEditing(true)
        tableViewImplement.saveBirthday { (success) in
            ProcessHUD.hideLoading()
            NotificationCenter.default.post(name: .AddNewBirthday, object: nil)
            self.dismissViewConroller()
        }
    }
    
    @objc func keyboardChangeAction(sender: Notification) {
        guard let userInfo = sender.userInfo else { return }
        let frame = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect
        let rect = tableView.rectForFooter(inSection: 0)
        guard let endFrame = frame else { return }
        let conFrame = self.view.convert(rect, from: tableView)
        if endFrame.minY < ScreenHeight {
            if endFrame.minY < conFrame.maxY {
                let offset = conFrame.maxY - endFrame.minY
                tableView.setContentOffset(CGPoint(x: 0, y: offset), animated: true)
            }
        } else {
            var point = CGPoint(x: 0, y: -tableView.contentInset.top)
            if #available(iOS 11.0, *) {
                point = CGPoint(x: 0, y: -tableView.adjustedContentInset.top)
            }
            tableView.setContentOffset(point, animated: true)
        }
    }
}
